package ass.web;

import java.io.IOException;
import java.util.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ass.beans.ReviewBean;
import ass.dao.support.MovieDAOImpl;
import ass.dao.support.ReviewDAOImpl;

/**
 * Servlet implementation class Review
 */
public class Review extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Review() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String rating = (String) request.getParameter("myrating");
		String review = (String) request.getParameter("myreview");
		String nickname = (String) request.getParameter("nickname");
		String movie_id = (String) request.getParameter("movieID");
		java.sql.Date date = new java.sql.Date( new java.util.Date ().getTime());
		
		ReviewDAOImpl reviewDAOImpl = new ReviewDAOImpl();
		
		ReviewBean reviewBean = new ReviewBean();
		
		reviewBean.setDate_added(date);
		reviewBean.setMovie_id(Integer.parseInt(movie_id));
		reviewBean.setRating(Integer.parseInt(rating));
		reviewBean.setNickname(nickname);
		reviewBean.setReview(review);
		
		
		reviewDAOImpl.insert(reviewBean);
		
		
		MovieDAOImpl movieDAOimpl = new MovieDAOImpl();
		List<ReviewBean> reviewBeanList = new ArrayList<ReviewBean>();
		reviewBeanList = reviewDAOImpl.getReviewByMovie(Integer.parseInt(movie_id));
		
		int d = 0;
		int s = 0;
		int avg = 0;
		if (reviewBeanList.isEmpty()) {
			
		} else {
			for (ReviewBean x : reviewBeanList) {

				s = s+ x.getRating();
				d++;
			}
			avg = s/d;
		}
		
		movieDAOimpl.update_rating(Integer.parseInt(movie_id), avg);
		
		String nextJSP = "/userSearchMDetail.jsp?id"+movie_id;
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(nextJSP);
		request.setAttribute("movieID", movie_id);
		request.setAttribute("reviewPosted", "<font color='green'>Review has been posted</font>");
		dispatcher.forward (request, response);
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
